import CryptoJS from "crypto-js";
// iv  偏移量
const iv = "FptBCcAh59H2Fr2M";

/**
 * 加密
 * @returns {string}
 * @param data  加密数据
 */
const encrypt = (data):string =>{
	const str:CryptoJS.lib.CipherParams|string = JSON.stringify(data);
	let key:string|undefined =  uni.getStorageSync("secret");
	if (key === "" || key == null) {
		key = "9oux2Y9ALwFcQaFj";
	}
	const mKey = CryptoJS.enc.Utf8.parse(key);
	const mIv = CryptoJS.enc.Utf8.parse(iv);
	const encrypted = CryptoJS.AES.encrypt(str, mKey, {
		iv: mIv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7,
	});
	return encrypted.toString(); // 返回的是base64格式的密文
};

/**
 * 解密
 * @param data 待解密字符串
 * @returns {string}
 */
const decrypt = ( data:string | CryptoJS.lib.CipherParams ):string => {
	// 获取用户key 如果不存在  使用默认key
	let key =  uni.getStorageSync("secret");
	if(key == null||key === ""){
		key = "9oux2Y9ALwFcQaFj";
	}
	const m_key = CryptoJS.enc.Utf8.parse(key);
	const m_iv = CryptoJS.enc.Utf8.parse(iv);
	// data = CryptoJS.enc.Base64.parse(data);
	const decrypted = CryptoJS.AES.decrypt(data, m_key, {
		iv: m_iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});
	return decrypted.toString(CryptoJS.enc.Utf8);
};
export {
	decrypt,
	encrypt
};